//骨傲天
import * as THREE from "../node_modules/three/build/three.module.js";
import { OrbitControls } from "../node_modules/three/examples/jsm/controls/OrbitControls.js";

let scene, camera, renderer, controls;

/**
 * 初始化
 */
function init() {
  scene = new THREE.Scene();
  // scene.background = new THREE.Color(0x55efc4);
  var bgTexture = new THREE.TextureLoader().load("../src/img/overlord.png");
  bgTexture.wrapS = THREE.RepeatWrapping;
  bgTexture.wrapT = THREE.RepeatWrapping;
  bgTexture.repeat.set(1, 1);
  scene.background = bgTexture;

  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  // camera.position.z = 180;
  camera.position.set(-26.044, -143.058, 18.731);
  camera.lookAt(new THREE.Vector3(0, 0, 0));
  scene.add(camera);

  renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  //鼠标控制器
  controls = new OrbitControls(camera, renderer.domElement);
  controls.update();
}

function createBox(size, posi) {
  let boxGeo = new THREE.BoxBufferGeometry(...size);
  let material = new THREE.MeshNormalMaterial();
  let box = new THREE.Mesh(boxGeo, material);
  box.position.set(...posi);
  scene.add(box);
  return box;
}

function animate() {
  requestAnimationFrame(animate);

  scene.children.forEach((cube) => {
    cube.rotation.x += Math.floor(Math.random() * 10) * 0.01;
    cube.rotation.y += Math.floor(Math.random() * 10) * 0.01;
  });

  controls.update();
  renderer.render(scene, camera);
}

/**
 *
 * @param {*} size 最大size
 * 只能水平平移
 * @param {*} min 最小范围
 * @param {*} max 最大范围
 */
function createRandomBoxInfo(boxSize, min, max) {
  //单个box的信息
  let size = [];
  let posi = [];

  for (let i = 1; i <= 3; i++) {
    let sizeItem = Math.round(Math.floor(Math.random() * boxSize) + 1);
    size.push(sizeItem);
    let posiItem = Math.round(
      Math.floor(Math.random() * (max - min + 1) + min)
    );
    posi.push(posiItem);
  }
  return {
    size,
    posi,
  };
}

init();

let max = 0,
  min = -100;
let boxSize = 5;

//生成个数
let count = 1000;

//收集box实例
let boxs = [];
for (let i = 1; i <= count; i++) {
  let info = createRandomBoxInfo(boxSize, min, max);
  let box = createBox(info.size, info.posi);
  boxs.push(box);
}

animate(boxs);

//输出camera位置信息,平移相机,设置方块显示位置
// document.querySelector("canvas").onclick = function () {
//   console.log(camera.position);
// };
